<html>
<head>
<title>Learn Japanese</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height" />

<link href="css/themes/default/jquery.mobile-1.2.0.min.css" rel="stylesheet" />
<link href="css/jqm-docs.css" rel="stylesheet" />
<link href="css/jquery.mobile.simpledialog.min.css" rel="stylesheet" />
<script src="js/serverconfig.js"></script>
<script src="js/jquery-1.8.2.js"></script>
<script src="js/jquery.mobile-1.2.0.min.js"></script>
<script src="js/jquery.mobile.simpledialog2.min.js"></script>
<script src="cordova-2.0.0.js"></script>

<style type="text/css">
.nav-glyphish .ui-btn .ui-btn-inner {
	padding-top: 80px !important;
}

.nav-glyphish .ui-btn .ui-icon {
	width: 80px !important;
	height: 80px !important;
	margin-left: -40px !important;
	box-shadow: none !important;
	-moz-box-shadow: none !important;
	-webkit-box-shadow: none !important;
	-webkit-border-radius: 0 !important;
	border-radius: 0 !important;
}

#vocabulary .ui-icon {
	background: url(img/vocabulary-128-icon.png) 50% 50% no-repeat;
	background-size: 60px 60px;
}

#kanji .ui-icon {
	background: url(img/kanji-128-icon.png) 50% 50% no-repeat;
	background-size: 60px 60px;
}

#grammar .ui-icon {
	background: url(img/grammar-128-icon.png) 50% 50% no-repeat;
	background-size: 60px 60px;
}

#reading .ui-icon {
	background: url(img/reading-128-icon.png) 50% 50% no-repeat;
	background-size: 60px 60px;
}

#listening .ui-icon {
	background: url(img/listening-128-icon.png) 50% 50% no-repeat;
	background-size: 60px 60px;
}

#about .ui-icon {
	background: url(img/about-128-icon.png) 50% 50% no-repeat;
	background-size: 60px 60px;
}


.ntc-chucnang.ui-btn-active {
	border: 1px solid #f4c63f;
	background: #fadb4e;
	font-weight: bold;
	color: #222;
	text-shadow: 0 1px 0 #fff;
	background-image: -webkit-gradient(linear, left top, left bottom, from(#ffefaa),
		to(#ffe155));
	background-image: -webkit-linear-gradient(#ffefaa, #ffe155);
	background-image: -moz-linear-gradient(#ffefaa, #ffe155);
	background-image: -ms-linear-gradient(#ffefaa, #ffe155);
	background-image: -o-linear-gradient(#ffefaa, #ffe155);
	background-image: linear-gradient(#ffefaa, #ffe155);
}
</style>
<script type="text/javascript">
if(localGet('daTaiPhanNghe',0) == 1 ) window.location="index.html";


var fileKaiwaList = new Array();	
var fileThumbList = new Array();	
var sourUrlList = new Array();	
var sourNameList = new Array();	
document.addEventListener("deviceready", checkConnection, false);

function checkConnection() {
    var networkState = navigator.network.connection.type;

   /*  var states = {};
    states[Connection.UNKNOWN]  = 'Unknown connection';
    states[Connection.ETHERNET] = 'Ethernet connection';
    states[Connection.WIFI]     = 'WiFi connection';
    states[Connection.CELL_2G]  = 'Cell 2G connection';
    states[Connection.CELL_3G]  = 'Cell 3G connection';
    states[Connection.CELL_4G]  = 'Cell 4G connection';
    states[Connection.NONE]     = 'No network connection'; */
	if(networkState == Connection.NONE){
		dialog(2);
	}
	else if(networkState == Connection.CELL_2G || networkState == Connection.CELL_3G || networkState == Connection.CELL_4G){
		dialog(3);
	}
	else downloadAll();
    
}

function localGet(item,defaultvalue){
	if(localStorage.getItem(item) != null) return localStorage.getItem(item);
	return defaultvalue;
}
function downloadAll(){
	db = window.openDatabase("JapaneseBasic", "1.0", "Japanese Database",500000);
	db.transaction(populateDB, function(err) {console.log("Error processing SQL: " + err.code);}, function(){console.log("success");});
}

function populateDB(tx) {
	var sql = "SELECT li_thumb, li_track  FROM listening";
	tx.executeSql(sql, [], function(tx, results){
		var len = results.rows.length;
		if (len > 0) {
			dialog(0);
			for (var i = 0; i < len; i++) {
				var data = results.rows.item(i);
				fileKaiwaList.push(data.li_track);
				fileThumbList.push(data.li_thumb);
			}
			for(var i = 0; i < fileKaiwaList.length; i++){
				sourUrlList.push(kaiwaUrl + "/" +  fileKaiwaList[i]);
				sourNameList.push(fileKaiwaList[i]);
				//alert(kaiwaUrl + "/" +  fileKaiwaList[i]);
				
			}
			for(var i = 0; i < fileThumbList.length; i++){
				sourUrlList.push(thumbUrl + "/" +  fileThumbList[i]);
				sourNameList.push(fileThumbList[i]);
				//alert(thumbUrl + "/" +  fileThumbList[i]);
			}
			
			UpdateFile();
		};
	});
}
function UpdateFile(){
	console.log("UpdateFile");
	window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
}
function onFileSystemSuccess(fileSystem) {
	alert("Chương trình cần khởi tạo các file nghe cần thiết. Bấm Ok để tiếp tục");
	fileSystem.root.getDirectory("MinanoNihongoListenning", {create: true, exclusive: false}, gotFileEntry, fail);
}

function fail(evt) {
	console.log(evt.target.error.code);
}
function gotFileEntry(fileEntry) {
	var desPath = fileEntry.fullPath+"/";
	localStorage.setItem("listenFilePath",desPath);
	var fileCount = sourUrlList.length;
	var fileCountDone = 0;
	//downloadFile("http://192.168.1.7/moSoap/nihongo/admin/audio/kaiwa/VediEm.mp3",'kkkk.mp3',desPath);
	if(sourUrlList.lenght != 0 && sourNameList!= 0){
		var sourUrl = sourUrlList.shift();
		var desName = sourNameList.shift();
		downloadFile(sourUrl,desName,desPath,fileCount,fileCountDone);
	}
	
}
 
function downloadFile(sourUrl,desName,desPath,fileCount,fileCountDone){
	console.log("download: "+ sourUrl);
//	alert("download: "+ sourUrl);
	var fileTransfer = new FileTransfer();
	fileTransfer.download(
		   sourUrl,
		   desPath + desName,
		   function(theFile) {
			   fileCountDone++;
			   console.log("download complete: " + theFile.toURI());
			   
			   //cập nhật process con mẹ nó  khó quá
			   $.mobile.sdCurrentDialog.updateBlank('<p stype="text-align:center">Xin chờ một lát </p><p stype="text-align:center"> Đã hoàn thành:  '+fileCountDone+'/'+fileCount+'</p><p stype="text-align:center">Đang tải file:'+ desName+' </p>');
			   
			 //download xong
			   if(sourUrlList.lenght != 0 && sourNameList.length != 0){
					var sourUrlt = sourUrlList.shift();
					var desNamet = sourNameList.shift();
					downloadFile(sourUrlt,desNamet,desPath,fileCount,fileCountDone);
				}else{
					if($.mobile.sdCurrentDialog != undefined) $.mobile.sdCurrentDialog.close(); else{
				 		$(".ui-simpledialog-container").hide();
				     	$(".ui-simpledialog-screen").hide();
				 	}
					dialog(1,fileCount,fileCountDone,fileCount-fileCountDone);
				}
				
			   
		   },
		   function(error) {
			   //alert("download fail: " + desName);
			   console.log("download error source " + error.source);
			   console.log("download error target " + error.target);
			   console.log("upload error code: " + error.code);
			   console.log("err: "+ sourUrl);
			   
			   //download xong
			   if(sourUrlList.lenght != 0 && sourNameList.length != 0){
					var sourUrlt = sourUrlList.shift();
					var desNamet = sourNameList.shift();
					downloadFile(sourUrlt,desNamet,desPath,fileCount,fileCountDone);
				}else{
					//dong cua so cho
					if($.mobile.sdCurrentDialog != undefined) $.mobile.sdCurrentDialog.close(); else{
				 		$(".ui-simpledialog-container").hide();
				     	$(".ui-simpledialog-screen").hide();
				 	}
					dialog(1,fileCount,fileCountDone,fileCount-fileCountDone);
				}
		   }
	);
}
// đậu xanh rau má
function dialog(type,totalCount,sucCount,errCount){
		if(type ==0 )$('<div>').simpledialog2({
		    mode: 'blank',
		    headerText: 'Đang tải các file nghe...',
		    headerClose: false,
		    blankContent : '<p style="align:center">Chương trình đang tải các file nghe. Vui lòng chờ trong khi chương trình đang tải dữ liệu. Vui lòng không tắt ứng dụng! <p>',
		  });
		if(type==1) $('<div>').simpledialog2({
				mode: 'button',
				headerText: 'Hoàn thành',
				headerClose: true,
				buttonPrompt: '<p>Đã tải xong các file nghe cần thiết. Bấm Đóng để tiếp tục </p><p>Tổng: '+totalCount+'</p> <p>Thành công: '+sucCount+'</p><p>Lỗi: '+errCount+'</p>',
				buttons : {
					'Đóng': {
						click: function (){
							localStorage.setItem('daTaiPhanNghe',1);
							 window.location="listening.html";
						}
					},
					
				}
			});
		if(type==2) $('<div>').simpledialog2({
				mode: 'button',
				headerText: 'Không có kết nối mạng ',
				headerClose: true,
				buttonPrompt: 'Không thể tải vì không có kết nối mạng ',
				buttons : {
					'Đóng': {
						click: function (){
							 window.location="index.html";
						}
					},
					
					
				}
			});
		if(type==3) $('<div>').simpledialog2({
				mode: 'button',
				headerText: 'Kết nối có thể tốn nhiều tiền',
				headerClose: true,
				buttonPrompt: 'Bạn đang không dùng kết nối mạng dữ liệu, khi download có thể gây tốn nhiều chi phí! Bạn nên sử dụng kết nối wifi để hạn chế chi phí. Bạn có muốn tiếp tục download các file nghe? ',
				buttons : {
					'OK': {
						click: function (){
							 downloadAll();
						}
					},
					'Để sau': {
						click: function (){
							 window.location="index.html";
						}
					},
					
					
				}
			});
}
</script>

</head>
<body>
	<div data-role="page" class="type-interior">
		<!-- Start Header -->
		<div data-role="header" data-theme="f" class="ntcHeader"
			data-position="fixed">
			<h1 style="text-transform: capitalize;">
				<b>みんなの日本語</b>
				
			</h1>
			
		</div>

	</div>
</body>
</html>